package org.example.controller;

import org.example.entity.Admin;
import org.example.entity.User;
import org.example.feign.AccountFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;

@Controller
@RequestMapping("/account")
public class AccountHandler {

    @Autowired
    private AccountFeign accountfeign;

    @GetMapping("/register")
    public String register() {
        return "redirect:/menu/redirect/register";
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("type") String type, HttpSession httpSession) {
        Object object = accountfeign.login(username, password, type);
        LinkedHashMap<String,Object> hashMap = (LinkedHashMap)object;//key.value
        String result = null;
        String idStr = null;
        long id = 0L;
        if (object == null) {
            result = "login";
        }else {
            switch (type) {
                case "user":
                    User user = new User();
                    idStr = hashMap.get("id")+"";
                    id = Long.parseLong(idStr);
                    String nickname = (String) hashMap.get("nickname");
                    user.setId(id);
                    user.setNickname(nickname);
                    httpSession.setAttribute("user", user);
                    result = "index";
                    break;
                case "admin":
                    Admin admin = new Admin();
                    idStr = hashMap.get("id")+"";
                    id = Long.parseLong(idStr);
                    String username2 = (String) hashMap.get("username");
                    admin.setId(id);
                    admin.setUsername(username2);
                    httpSession.setAttribute("admin", admin);
                    result = "main";
                    break;
            }
        }
        return result;
    }

    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {
        httpSession.invalidate();
        return "redirect:/menu/redirect/login.html";
    }

    @GetMapping("/redirect/order")
    public String redirectOrder() {
        return "redirect:/menu/redirect/person_order"; // 重定向到订单页面
    }

    @GetMapping("/redirect/index")
    public ModelAndView index() {
        ModelAndView view = new ModelAndView();
        view.setViewName("index");
        return view; // 重定向到订单页面
    }

}
